import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';

const TARGET_DIR = 'dist'; // 目标目录
const TARGET_REMOTE = 'origin'; // 远程仓库名称
const TARGET_BRANCH = 'bundle2'; // 目标分支名称
const BUNDLE_SCRIPT = 'pnpm build'; // 打包脚本
const COMMIT_MESSAGE = 'bundle'; // 提交信息

// 执行命令并返回输出
function execCommand(command, inherit = false) {
    return execSync(command, { encoding: 'utf-8', stdio: inherit ? 'inherit' : 'pipe' })?.trim();
}

// 检查目录是否存在
function directoryExists(dirPath) {
    return fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
}

// 删除目录
function deleteDirectory(dirPath) {
    if (directoryExists(dirPath)) {
        fs.rmSync(dirPath, { recursive: true, force: true });
        console.log(`Removed "${dirPath}" directory.`);
    }
}

// 检查工作区是否有更改（未暂存的修改或新文件）。
function hasUnstagedChanges() {
    try {
        return execCommand('git status --porcelain').length > 0;
    } catch (error) {
        return false;
    }
}

// 检查是否有已暂存但未提交的更改。
function hasStagedChanges() {
    try {
        execCommand('git diff --cached --exit-code');
        return false; // 返回 0，表示没有已暂存的更改
    } catch (error) {
        return true; // 返回非 0，表示有已暂存的更改
    }
}

function main() {
    try {
        // 获取远程仓库地址
        const remoteUrl = execCommand(`git remote get-url ${TARGET_REMOTE}`);
        console.log(`Remote URL: ${remoteUrl}`);

        // 删除旧的 bundle 目录
        deleteDirectory(TARGET_DIR);

        // 检查远程分支是否存在
        let isRemoteBranchExist = false;
        try {
            if (execCommand(`git ls-remote ${TARGET_REMOTE} refs/heads/${TARGET_BRANCH}`)) {
                isRemoteBranchExist = true;

                console.log(`Remote branch "${TARGET_BRANCH}" exists.`);

                // 克隆远程分支到本地目录
                execCommand(`git clone ${remoteUrl} --branch ${TARGET_BRANCH} ${TARGET_DIR}`, true);
            }
        } catch (error) {
            console.log(`Remote branch "${TARGET_BRANCH}" does not exist`);
        }

        // 运行打包脚本
        execCommand(BUNDLE_SCRIPT, true);

        process.chdir(TARGET_DIR);
        console.log(`Changed working directory to "${TARGET_DIR}"`);

        if (!isRemoteBranchExist) {
            // 初始化 Git 仓库
            execCommand(`git init --initial-branch=${TARGET_BRANCH}`, true);
        }

        if (hasUnstagedChanges()) {
            execCommand('git add -A', true);

            if (hasStagedChanges()) {
                execCommand(`git commit -m "${COMMIT_MESSAGE}"`, true);

                if (!isRemoteBranchExist) {
                    execCommand(`git push --set-upstream ${remoteUrl} ${TARGET_BRANCH}`, true);
                } else {
                    execCommand('git push', true);
                }

                console.log('Bundle operation completed successfully');
            } else {
                console.log('No staged changes found');
            }
        } else {
            console.log('No unstaged changes found');
        }

        // 删除 .git 目录
        deleteDirectory(path.join(TARGET_DIR, '.git'));
    } catch (error) {
        console.error(`[ERROR] ${error.message}`);
        process.exit(1);
    }
}

main();
